package com.hk.kindheartedness;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.model.User;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.Objects;

/**
 * 登录
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String USER_TYPE_PATIENT = "患者";
    private static final String USER_TYPE_DOCTOR = "医生";
    private static final String USER_TYPE_BUYER = "采购员";
    private static final String USER_TYPE_ADMIN  = "管理员";

    //    Initialize Toast
    private Toast toast;

    //    定义一个常量，记录两次点击后退按钮的时间差
    private Long exitTime = 0L;

    //    Initialize intent
    private Intent intent;
    //    Initialize spinner
    private Spinner userType;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

//    声明全局用户登录类型
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
//        实例化
        dbOpenHelper = new DBOpenHelper(LoginActivity.this, "db_kindheartedness", null, 1);
//        获取按钮控制权
        Button loginBtn = findViewById(R.id.loginBtn);
        Button newUserRegister = findViewById(R.id.newUserRegister);
        Button whatPwd = findViewById(R.id.whatPwd);
        loginBtn.setOnClickListener(this);
        newUserRegister.setOnClickListener(this);
        whatPwd.setOnClickListener(this);
//        获取登录账户类型
        userType = findViewById(R.id.userType);
        userType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type = (String) userType.getSelectedItem();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


    }


    /**
     * 点击事件
     * @param v
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            登录
            case R.id.loginBtn:
                login();
                break;
//                新用户注册
            case R.id.newUserRegister:
                intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                break;
//                忘记密码
            case R.id.whatPwd:
                // TODO: 2022/3/13 有时间补充忘记密码功能
                ToastUtil.toastHint(toast,LoginActivity.this,"功能即将上线！");
                break;
            default:
                break;
        }

    }

    /**
     * 登录逻辑
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void login() {
//        获取登录输入信息
        String loginPhone = ((EditText)findViewById(R.id.loginPhone)).getText().toString();
        String loginPwd = ((EditText)findViewById(R.id.loginPwd)).getText().toString();
//        类型 0： 患者 1：医生  2：管理员 3：采购员（进药物的）
        String userType = type.equals(USER_TYPE_PATIENT) ? "0" : type.equals(USER_TYPE_DOCTOR) ? "1" : type.equals(USER_TYPE_ADMIN) ? "2" : "3";
        Log.i("登录设备类型：",userType);
        Log.i("loginPhone：",loginPhone);
        Log.i("loginPwd：",loginPwd);
//        获取到数据库操作对象SQLiteDatabase
        SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
//        条件赋值
        String[] where = {userType,loginPhone,loginPwd};
        Cursor query = database.query("user", null, "type = ? and phone = ? and password = ? ", where, null, null,null);
        User user = null;
        while (query.moveToNext()) {
            user = new User();
//            列，按从左到右排序，索引0开始
            String id = query.getString(0);
            String userName = query.getString(1);
            String phone = query.getString(2);
            String loginType = query.getString(4);
            user.setId(Integer.parseInt(id));
            user.setUserName(userName);
            user.setPhone(phone);
            user.setType(Integer.valueOf(loginType));
//            如果是医生登录，获取医生ID
            if ("1".equals(userType)) {
                String type = query.getString(10);
                Integer doctorId = Integer.valueOf(type);
                user.setDoctorId(doctorId);
            }
        }
        if (Objects.nonNull(user)) {
            // TODO: 2022/3/14 编写具体登录实现逻辑
//        类型 0： 患者 1：医生  2：管理员 3：采购员（进药物的）
            Integer type = user.getType();
            if (type == 0) { // 患者
                intent = new Intent(LoginActivity.this,PatientMainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("loginUserId",user.getId().toString());
                bundle.putString("loginPhone",user.getPhone());
                bundle.putString("loginType",user.getType().toString());
                bundle.putString("userName",user.getUserName());
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
                return;
            } else if (type == 1) { // 医生
                intent = new Intent(LoginActivity.this,DoctorMainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("loginDoctorId",user.getDoctorId().toString());
                bundle.putString("loginPhone",user.getPhone());
                bundle.putString("loginType",user.getType().toString());
                bundle.putString("userName",user.getUserName());
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
            } else if (type == 2) { //管理员 已完成
                intent = new Intent(LoginActivity.this,AdminActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("loginPhone",user.getPhone());
                bundle.putString("loginType",user.getType().toString());
                bundle.putString("userName",user.getUserName());
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
                return;
            } else if (type == 3) { // 采购员
                toast = ToastUtil.toastHint(toast,LoginActivity.this,"功能暂未开放,敬请期待！");
                return;
            }
            return;
        }
        toast = ToastUtil.toastHint(this.toast, LoginActivity.this, "登录失败！请检查账号/密码/类型!");
        return;
    }

    //    重写onKeyDown()方法来拦截用户单击后退按钮事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        判断按下的是否为后退按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //    创建退出方法
    private void exit() {
//        判断两次点击的时间差 大于2秒钟
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            toast = ToastUtil.toastHint(this.toast, LoginActivity.this, "再按一次退出程序！");
            exitTime = System.currentTimeMillis();
        } else {
//            关闭当前Activity
            finish();
//            关闭程序
            System.exit(0);
        }
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}